<template>
  <van-nav-bar
    class="vnb"
    title="排行榜"
    left-arrow
    @click-left="handleBack"
  />
  <menu-bar
    class="mb"
    :menus="menus"
    :current-path="currentPath"
  />
  <load-more ref="listRef" @refresh="handleRefresh" @load="handleLoad">
    <div class="row" v-for="(item, index) in pageList" :key="item.bvid">
        <div class="order">{{index + 1}}</div>
        <video-cover 
          class="content" 
          direction="horizontal"
          :danmaku="item.video_review"              
          v-bind="item"
        ></video-cover>
    </div>
  </load-more>
</template>

<script>
import { reactive, toRefs, computed, watch, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import * as types from '@/store/mutation-types'
import { NavBar as VanNavBar } from 'vant'
import MenuBar from '@/components/MenuBar'
import LoadMore from '@/components/LoadMore'
import VideoCover from '@/components/VideoCover'
import MenuConfig from '@/router/menu'
import checkUrl from '@/views/Channel/hooks/checkUrl'
import { rankApi } from '@/api'
export default {
  name: 'Rank',
  components: {
    VanNavBar,
    MenuBar,
    LoadMore,
    VideoCover
  },
  props: {
    id: {
      type: [Number, String]
    }
  },
  // 校验地址是否有效
  beforeRouteEnter(to, from, next) {       
    const isValid = checkUrl(to.params)  
    if (isValid) {
      next()
    } else {
      next({ path: '404' })
    }
  },
  setup(props) {
    const store = useStore()
    const router = useRouter()
    const params = reactive({
      listRef: null,
      rid: computed(() => {
        let rid = 0
        rid = (props.id - 0) === 167 ? 168 : props.id
        return rid
      }),
      menus: computed(() => {
        const arr = []
        for (const c of MenuConfig) {
          const { name, tid, route, hide } = c
          if (hide) {
            continue
          }
          arr.push({
            title: name === '首页' ? '全站' : name,
            path: route === '/' ? '/rank' : `/rank/${tid}`,
            currentPage: 1,
            totalPage: 0,
            pageSize: 20,
            list: []
          })
        }
        return arr
      }),
      currentPath: computed(() => {
        return `/rank${props.id ? ('/' + props.id) : ''}`
      }),
      pageList: []
    })

    
    const getCurrent = () => {        
      return params.menus.find(item => item.path === params.currentPath)
    }
    const handleBack = () => {
      router.go(-1)
    }

    const getData = async () => {
      try {
        startLoading()
        const { data } = await rankApi.getRank({
          rid: params.rid
        })
        const { list } = data
        const current = getCurrent()
        if (!Array.isArray(list)) {
          return
        }
        if (list.length === 0) {
          current.totalPage = 0
          current.list = []
          complete()
        } else {          
          current.totalPage = Math.ceil(list.length / current.pageSize)
          current.list = list          
        }    
        setPageList()        
      } catch (error) {
        console.log(error)
      } finally {
        stopRefresh()
      }
    }

    const startLoading = () => {
      params.listRef?.startLoad()
    }
    const stopLoading = () => {
      params.listRef?.stopLoad()
    }
    const stopRefresh = () => {
      params.listRef?.stopRefresh()
    }
    const complete = () => {
      params.listRef?.completeLoad()
    }

    const handleLoad = () => {
      const current = getCurrent()
      const { totalPage, currentPage } = current
      if (currentPage < totalPage) {
        current.currentPage = currentPage + 1    
        setPageList()   
      } else {
        complete()
      }
      stopLoading()
    }

    const handleRefresh = () => {
      const current = getCurrent()
      current.currentPage = 1        
      getData()
    }

    const setPageList = () => {
      const current = getCurrent()
      params.pageList = current.list.slice(0, current.currentPage * current.pageSize)  
    }

    // 设置头部显示状态
    store.commit(types.SET_HEADER, false)
    
    onBeforeUnmount(() => {
      store.commit(types.SET_HEADER, true)
    })

    watch(() => props.id, () => {
      const current = getCurrent()
      if (!current.list.length) {
        handleRefresh()
      } else {
        setPageList()
      }      
    }, {
      immediate: true
    })    

    return {
      ...toRefs(params),
      handleBack,
      handleLoad,
      handleRefresh
    }
  }
}
</script>

<style lang="scss" scoped>
  .vnb{
    position: sticky;
    top: 0;
    z-index: 2;
    height: 46px;
  }
  .vnb :deep {
    .van-nav-bar__title, .van-nav-bar__arrow {
      color: $theme-color;
      font-size: 16px;
    }
  }
  .mb {
    position: sticky;
    top: 46px;
    z-index: 2;
  }
  .row{
      display: flex;
      &:nth-child(1),
      &:nth-child(2),
      &:nth-child(3) {
          .order{
              text-indent: 999px;
          }
      }   
      &:nth-child(1) {
          .order{
            background-image: url('~@/assets/images/rank1.png')
          }
        }
        &:nth-child(2) {
          .order{
            background-image: url('~@/assets/images/rank2.png')
          }
        }
        &:nth-child(3) {
          .order{
            background-image: url('~@/assets/images/rank3.png')
          }
        }
  }
  .order{
      width: 30px;
      display: flex;
      align-items: center;
      text-indent: 8px;
      color: $color-text-regular;
      font-size: 14px;
      background-repeat: no-repeat;
      background-size: 60%;
      background-position: 50%;
  }
  .content {
      flex: 1;
  }
</style>